import { AfterViewInit, Component, OnDestroy, OnInit } from '@angular/core';
import { WebGLService } from 'src/app/services/webgl.service';

@Component({
    selector: 'color-triangle',
    templateUrl: './color-triangle.component.html',
    styleUrls: ['./color-triangle.component.scss']
})
export class ColorTriangleComponent implements OnInit, AfterViewInit, OnDestroy {
    // 顶点着色器
    private vertexShaderSource = `
        attribute vec4 a_Position;
        attribute vec4 a_Color;
        varying vec4 v_Color;
        void main () {
            gl_Position = a_Position;
            v_Color = a_Color;
        }  
    `;
    private fragShaderSource = `
        precision mediump float;
        varying vec4 v_Color;
        void main () {
            gl_FragColor = v_Color;
        }
    `;
    private gl: WebGLRenderingContext;

    constructor(private webglService: WebGLService) { }
    ngOnInit() { }
    ngAfterViewInit () {
        this.init();
    }
    ngOnDestroy () {}

    private init () {
        const canvas = document.querySelector('#myCanvas') as HTMLCanvasElement;
        this.gl = canvas.getContext('webgl');

        // 初始化 shader
        this.webglService.initShader(this.gl, this.vertexShaderSource, this.fragShaderSource);

        // 初始化 VertexBuffer
        const n = this.initVertexBuffer(this.gl);

        const program = this.webglService.getProgramByGLContext(this.gl);
        
        // 设置背景颜色
        this.gl.clearColor(0.0, 0.0, 0.0, 1.0);
        this.gl.clear(this.gl.COLOR_BUFFER_BIT);

        // 画点
        this.gl.drawArrays(this.gl.TRIANGLES, 0, n);
    }

    private initVertexBuffer (gl: WebGLRenderingContext) {
        const vertices = new Float32Array([
            //x     y   
            0.0,    0.5,    1.0,    0.0,    0.0,
           -0.5,   -0.5,    0.0,    1.0,    0.0,   
            0.5,   -0.5,    0.0,    0.0,    1.0,
        ]);
        const n = 3;    // 点的个数
        const byteLen = vertices.BYTES_PER_ELEMENT;

        // 创建缓冲区对象
        const vertexBuffer = gl.createBuffer();
        
        // 将缓冲区对象绑定到目标
        gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);

        // 向缓冲区对象中写入数据
        gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

        const program = this.webglService.getProgramByGLContext(gl);
        const a_Position = gl.getAttribLocation(program, 'a_Position');
        const a_Color = gl.getAttribLocation(program, 'a_Color');

        // 将缓冲区对象分配给 a_Position 变量
        gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 5 * byteLen, 0);
        gl.vertexAttribPointer(a_Color, 3, gl.FLOAT, false, 5 * byteLen, 2 * byteLen);

        // 连接 a_Position 变量与分配给它的缓冲区对象
        gl.enableVertexAttribArray(a_Position);
        gl.enableVertexAttribArray(a_Color);

        return n;
    }
}